﻿using AutoMapper;
using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.BasicInformation.Departments;
using THE_WIND_RISES.Common.Dtos;

namespace Enterprise_Set.API.Application.Commands.Week1.BusinessEntities
{
    /// <summary>
    /// 部门添加
    /// </summary>
    public class DepartmentCreateHandler : IRequestHandler<DepartmentCreateCommand,Result>
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IBaseRepository<Department> departmentRepository;
        /// <summary>
        /// 自动映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        /// <param name="mapper"></param>
        public DepartmentCreateHandler(IBaseRepository<Department> departmentRepository, IMapper mapper)
        {
            this.departmentRepository = departmentRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartmentCreateCommand request, CancellationToken cancellationToken)
        {
            var result= new Result() { Code=(int)CommonErrorCodes.Added};

            try
            {
                var AddData = mapper.Map<Department>(request);

                string sql = "insert into Department values(@DepartmentId,@DepartmentStatus,@NodeEncoding,@DepartmentName,@EnterpriseId,@PId,@IsDelete)";
                //var AddNum = departmentRepository.Add(sql, AddData);
                var AddNum = departmentRepository.Add(sql, new Department()
                {
                    DepartmentId = AddData.DepartmentId,
                    DepartmentStatus = AddData.DepartmentStatus,
                    NodeEncoding = AddData.NodeEncoding,
                    DepartmentName = AddData.DepartmentName,
                    EnterpriseId = AddData.EnterpriseId,
                    PId = AddData.PId,
                    IsDelete = AddData.IsDelete,
                });
                if (AddNum > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
